import React, { useState, useEffect } from 'react';
import { Analytics } from '@/services/analytics';
import { SimpleBarChart, SimplePieChart, SimpleLineChart } from '@/components/charts/SimpleCharts';
import { Button } from '@/components/ui/Button';
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';

interface AnalyticsData {
  summary: {
    totalSchemes: number;
    totalColors: number;
    averageHarmony: number;
    mostProductiveDay: string;
  };
  trends: {
    weeklyActivity: { week: string; count: number }[];
    colorPreferences: { color: string; percentage: number }[];
    typeDistribution: { type: string; count: number }[];
  };
  recommendations: string[];
  insights: string[];
}

export const AnalyticsPage: React.FC = () => {
  const [data, setData] = useState<AnalyticsData | null>(null);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    loadAnalyticsData();
  }, []);

  const loadAnalyticsData = async () => {
    try {
      setIsLoading(true);
      setError(null);
      
      const [report, insights] = await Promise.all([
        Analytics.generateUsageReport(),
        Analytics.generateInsights()
      ]);
      
      setData({
        ...report,
        insights
      });
    } catch (err) {
      setError('加载分析数据失败');
      console.error('Failed to load analytics data:', err);
    } finally {
      setIsLoading(false);
    }
  };

  if (isLoading) {
    return (
      <div className="flex items-center justify-center h-64">
        <LoadingSpinner size="large" />
        <span className="ml-3 text-gray-600">正在分析数据...</span>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-12">
        <div className="text-red-500 mb-4">{error}</div>
        <Button onClick={loadAnalyticsData}>重新加载</Button>
      </div>
    );
  }

  if (!data) {
    return (
      <div className="text-center py-12">
        <p className="text-gray-600 mb-4">暂无分析数据</p>
        <Button onClick={() => window.location.href = '/color-picker'}>
          开始创建色彩方案
        </Button>
      </div>
    );
  }

  const typeNames: { [key: string]: string } = {
    'complementary': '互补色',
    'analogous': '类似色',
    'triadic': '三角色',
    'tetradic': '四角色',
    'monochromatic': '单色调',
    'custom': '自定义'
  };

  return (
    <div className="space-y-6">
      {/* 页面标题 */}
      <div className="flex items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold text-gray-900">数据分析</h1>
          <p className="text-gray-600">深入了解您的色彩使用习惯和趋势</p>
        </div>
        <Button onClick={loadAnalyticsData} variant="outline">
          刷新数据
        </Button>
      </div>

      {/* 概览统计 */}
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6">
        <div className="bg-white rounded-lg shadow-md p-6">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-blue-100 text-blue-600">
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
              </svg>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">总方案数</p>
              <p className="text-2xl font-bold text-gray-900">{data.summary.totalSchemes}</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-md p-6">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-green-100 text-green-600">
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4z" />
              </svg>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">总颜色数</p>
              <p className="text-2xl font-bold text-gray-900">{data.summary.totalColors}</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-md p-6">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-purple-100 text-purple-600">
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
              </svg>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">平均和谐度</p>
              <p className="text-2xl font-bold text-gray-900">{data.summary.averageHarmony.toFixed(1)}%</p>
            </div>
          </div>
        </div>

        <div className="bg-white rounded-lg shadow-md p-6">
          <div className="flex items-center">
            <div className="p-3 rounded-full bg-orange-100 text-orange-600">
              <svg className="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
              </svg>
            </div>
            <div className="ml-4">
              <p className="text-sm font-medium text-gray-500">最活跃日期</p>
              <p className="text-lg font-bold text-gray-900">
                {new Date(data.summary.mostProductiveDay).toLocaleDateString('zh-CN', {
                  month: 'short',
                  day: 'numeric'
                })}
              </p>
            </div>
          </div>
        </div>
      </div>

      {/* 图表区域 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* 每周活动趋势 */}
        <SimpleLineChart
          title="每周创作活动"
          data={data.trends.weeklyActivity.map(item => ({
            x: new Date(item.week).toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' }),
            y: item.count
          }))}
        />

        {/* 配色类型分布 */}
        <SimplePieChart
          title="配色类型分布"
          data={data.trends.typeDistribution.map((item, index) => ({
            label: typeNames[item.type] || item.type,
            value: item.count,
            color: `hsl(${(index * 360) / data.trends.typeDistribution.length}, 70%, 50%)`
          }))}
        />
      </div>

      {/* 色彩偏好分析 */}
      <SimpleBarChart
        title="色彩偏好分析"
        data={data.trends.colorPreferences.map(item => ({
          label: item.color,
          value: item.percentage,
          color: item.color === '红色' ? '#EF4444' :
                 item.color === '橙色' ? '#F97316' :
                 item.color === '黄色' ? '#EAB308' :
                 item.color === '绿色' ? '#22C55E' :
                 item.color === '青色' ? '#06B6D4' :
                 item.color === '蓝色' ? '#3B82F6' :
                 item.color === '紫色' ? '#8B5CF6' : '#EC4899'
        }))}
      />

      {/* 个人洞察 */}
      <div className="bg-white rounded-lg shadow-md p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">个人洞察</h3>
        <div className="space-y-3">
          {data.insights.map((insight, index) => (
            <div key={index} className="flex items-start">
              <div className="flex-shrink-0 w-2 h-2 bg-blue-500 rounded-full mt-2 mr-3" />
              <p className="text-gray-700">{insight}</p>
            </div>
          ))}
        </div>
      </div>

      {/* 改进建议 */}
      <div className="bg-gradient-to-r from-blue-50 to-purple-50 rounded-lg p-6">
        <h3 className="text-lg font-semibold text-gray-900 mb-4">💡 改进建议</h3>
        <div className="space-y-3">
          {data.recommendations.map((recommendation, index) => (
            <div key={index} className="flex items-start">
              <div className="flex-shrink-0 w-2 h-2 bg-purple-500 rounded-full mt-2 mr-3" />
              <p className="text-gray-700">{recommendation}</p>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

export const SettingsPage: React.FC = () => {
  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-2xl font-bold text-gray-900">设置</h1>
        <p className="text-gray-600">个性化你的应用体验</p>
      </div>
      
      <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
        <h3 className="text-lg font-medium text-yellow-800">功能开发中</h3>
        <p className="text-yellow-700 mt-1">
          设置页面正在开发中，敬请期待！将包括主题设置、语言选择、偏好配置等功能。
        </p>
      </div>
    </div>
  );
};